package com.aiti.lulian.service.impl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.uuid.UUIDUtil;
import com.aiti.lulian.dto.CardEnterpriseTemplateDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.entity.newCard.CardLinkInfo;
import com.aiti.lulian.entity.newCard.CardStyleFieldData;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardEnterpriseTemplateMapper;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.aiti.lulian.mapper.newCard.CardAuditMapper;
import com.aiti.lulian.mapper.newCard.CardLinkInfoMapper;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.mapper.newCard.CardStyleFieldDataMapper;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.CardEnterpriseTemplateBatchVo;
import com.aiti.lulian.vo.CardEnterpriseTemplateVo;
import com.aiti.lulian.vo.newCard.UserCardRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class CardEnterpriseTemplateServiceImpl extends BaseSerivceImpl<CardEnterpriseTemplateMapper, CardEnterpriseTemplate> implements CardEnterpriseTemplateService {
    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;
    @Autowired
    private CardTemplateStyleFieldService styleFieldService;

    @Autowired
    private CardTemplateStyleService templateStyleService;

    @Autowired
    private CardTemplateBackgroundService templateBackgroundService;

    @Autowired
    private ILuLianEnterpriseService enterpriseService;
    @Autowired
    private CardTemplateStyleService cardTemplateStyleService;
    @Autowired
    private CardTemplateBackgroundService cardTemplateBackgroundService;
    @Autowired
    private CardTemplateStyleFieldService cardTemplateStyleFieldService;

    @Autowired
    private CloudShowManagerSubService managerSubService;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardLinkInfoMapper cardLinkInfoMapper;
    @Autowired
    private CardAuditMapper cardAuditMapper;
    @Autowired
    private CardStyleFieldDataMapper cardStyleFieldDataMapper;


    @Override
    public Message saveTemplate(CardEnterpriseTemplate cardEnterpriseTemplate) {
        String baseId = cardEnterpriseTemplate.getBaseId();
        if(StringUtils.isEmpty(baseId)){
            cardEnterpriseTemplate.setBaseId(UUIDUtil.getUUID2());
            this.save(cardEnterpriseTemplate);
        }else{
            this.updateById(cardEnterpriseTemplate);
        }
        return Message.success();
    }

    @Override
    public Message getByEnterpriseId(String enterpriseId) {
        LambdaQueryWrapper<CardEnterpriseTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardEnterpriseTemplate::getEnterpriseId,enterpriseId).eq(CardEnterpriseTemplate::getIsDelete,0);
        List<CardEnterpriseTemplate> list = this.list(wrapper);
        return Message.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message deleteTemplate(String baseId) {
        this.removeById(baseId);
        //cardTemplateStyleService.remove(new LambdaQueryWrapper<CardTemplateStyle>().eq(CardTemplateStyle::getTemplateId,baseId));
        cardTemplateBackgroundService.remove(new LambdaQueryWrapper<CardTemplateBackground>().eq(CardTemplateBackground::getTemplateId,baseId));
        cardTemplateStyleFieldService.remove(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getTemplateId,baseId));
        managerSubService.removeUserTemplateByTemplateId(baseId);
        return Message.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message saveTemplateBatch(CardEnterpriseTemplateBatchVo cardEnterpriseTemplateBatchVo) {
        List<CardEnterpriseTemplate> templateList = cardEnterpriseTemplateBatchVo.getTemplateList();
        if(!CollectionUtils.isEmpty(templateList)){

            this.saveOrUpdateBatch(templateList);
        }
        return Message.success();
    }

    @Override
    public Message selectList(CardEnterpriseTemplateVo cardEnterpriseTemplate) {
        LambdaQueryWrapper<CardEnterpriseTemplate> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(cardEnterpriseTemplate.getLayoutNum())) {
            wrapper.eq(CardEnterpriseTemplate::getLayoutNum, cardEnterpriseTemplate.getLayoutNum());
        }else{
            wrapper.apply(" 1=1 ");
        }
        if("00".equals(cardEnterpriseTemplate.getType())){
            wrapper.apply(" enterprise_id is null ");
        }else if("01".equals(cardEnterpriseTemplate.getType())){
            wrapper.apply(" enterprise_id ={0}", cardEnterpriseTemplate.getEnterpriseId());
        }else if("02".equals(cardEnterpriseTemplate.getType())){
            wrapper.apply(" (enterprise_id ={0} or enterprise_id is null) ", cardEnterpriseTemplate.getEnterpriseId());
        }else{
            return Message.fail("type参数异常");
        }
        return Message.success(this.list(wrapper));
    }

//    @Override
//    public Message templateDetail(String baseId, String enterpriseId, String userId, boolean appFlag) {
//        CardEnterpriseTemplate template = this.getById(baseId);
//        CardEnterpriseTemplateDto cardEnterpriseTemplateDto = new CardEnterpriseTemplateDto();
//        if(null == template){
//            return Message.fail("模板不存在");
//        }else{
//            Message message = managerSubService.getUserInfo(userId);
//            if (message == null) {
//                return Message.fail("获取用户信息失败！");
//            }
//            Object obj = message.getObj();
//            if (obj == null) {
//                return Message.fail("获取用户信息失败！");
//            }
//            if (message.getCode() == 1) {
//                return Message.fail("查询用户信息错误");
//            }
//            ObjectMapper mapper = new ObjectMapper();
//            Map resultMap = mapper.convertValue(obj, Map.class);
//
//            String logo = template.getLogo();
//            LuLianEnterprise enterprise = enterpriseService.getById(enterpriseId);
//            if(StringUtils.isEmpty(logo)){
//                String enterpriseLogo = enterprise.getLogo();
//                if(!StringUtils.isEmpty(enterpriseLogo) && StringUtils.isEmpty(template.getLogo())){
//                    LambdaUpdateWrapper<CardEnterpriseTemplate> updateWrapper = new LambdaUpdateWrapper<>();
//                    updateWrapper.set(CardEnterpriseTemplate::getLogo, enterpriseLogo)
//                            .eq(CardEnterpriseTemplate::getBaseId, baseId);
//                    this.update(updateWrapper);
//                    template.setLogo(enterpriseLogo);
//                }
//            }
//
//            String styleId = template.getLayoutNum();
//            if(!StringUtils.isEmpty(styleId)){
//                CardTemplateStyle style = templateStyleService.getStyleById(styleId, baseId);
//                BeanUtils.copyProperties(template, cardEnterpriseTemplateDto);
//                List<CardTemplateStyleField> fieldList = style.getFieldList();
//                if(!CollectionUtils.isEmpty(fieldList)){
//                    extracted(appFlag, fieldList, resultMap, enterprise);
//                }
//                cardEnterpriseTemplateDto.setFieldList(fieldList);
//
//            }else{
//                cardEnterpriseTemplateDto.setFieldList(new ArrayList<CardTemplateStyleField>());
//            }
//
//        }
//
//
//        return Message.success(cardEnterpriseTemplateDto);
//    }



    @Override
    public Message saveTemplate(CardEnterpriseTemplateDto dto) {
        dto.setBaseId(UUIDUtil.getUUID());
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        processTemplateInfo(dto, true);
        BeanUtils.copyProperties(dto, template);
        this.save(template);
        return Message.success();
    }

    @Override
    public Message updateTemplate(CardEnterpriseTemplateDto dto) {
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        processTemplateInfo(dto, false);
        BeanUtils.copyProperties(dto, template);
        this.updateById(template);
        return Message.success();
    }

    @Override
    public Message enterpriseTemplateList(String enterpriseId) {
        LambdaQueryWrapper<CardEnterpriseTemplate> wrapper = new LambdaQueryWrapper<CardEnterpriseTemplate>().eq(CardEnterpriseTemplate::getEnterpriseId, enterpriseId).orderByAsc(CardEnterpriseTemplate::getBaseCreateTime);
        List<CardEnterpriseTemplate> list = this.list(wrapper);
        return Message.success(list);
    }

    @Override
    public Message userTemplateList(String enterpriseId, String userId) {
        Message message = managerSubService.getUserInfo(userId);
        if (message == null) {
            return Message.fail("获取用户信息失败！");
        }
        Object obj = message.getObj();
        if (obj == null) {
            return Message.fail("获取用户信息失败！");
        }
        if (message.getCode() == 1) {
            return Message.fail("查询用户信息错误");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map resultMap = mapper.convertValue(obj, Map.class);
        String backgroundIds = (String)resultMap.get("backgroundId");
        if(!StringUtils.isEmpty(backgroundIds)){
            List<String> templateIds = new ArrayList<>(Arrays.asList(backgroundIds.split(",")));
            List<CardEnterpriseTemplate> list = this.list(new LambdaQueryWrapper<CardEnterpriseTemplate>().in(CardEnterpriseTemplate::getBaseId, templateIds));
            return Message.success(list);
        }else{
            return Message.success(new ArrayList());
        }


    }

    @Override
    public Message templateStyleDetail(String styleId, String templateId, String cardId, String templateType) {
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
//        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
//        if(cardBaseInfo == null){
//            return Message.fail("该用户名片不存在");
//        }


        if(!StringUtils.isEmpty(templateId)){
            template = this.getById(templateId);

        }
//        if(StringUtils.isEmpty(template.getLogo())){
//            String enterpriseLogo = enterprise.getLogo();
//            if(StringUtils.isEmpty(template.getLogo())){
//                template.setLogo(enterpriseLogo);
//            }
//        }
        CardEnterpriseTemplateDto cardEnterpriseTemplateDto = new CardEnterpriseTemplateDto();
        BeanUtils.copyProperties(template, cardEnterpriseTemplateDto);
        if(!StringUtils.isEmpty(styleId)){

//            Message message = managerSubService.getUserInfo(userId);
//            if (message == null) {
//                return Message.fail("获取用户信息失败！");
//            }
//            Object obj = message.getObj();
//            if (obj == null) {
//                return Message.fail("获取用户信息失败！");
//            }
//            if (message.getCode() == 1) {
//                return Message.fail("查询用户信息错误");
//            }
//            ObjectMapper mapper = new ObjectMapper();
//            Map resultMap = mapper.convertValue(obj, Map.class);


            CardTemplateStyle cardTemplateStyle = cardTemplateStyleService.styleDetail(styleId, templateId, templateType);
            List<CardTemplateStyleField> fieldList = cardTemplateStyle.getFieldList();
//            if(!CollectionUtils.isEmpty(fieldList)){
//                extracted(false, fieldList, cardBaseInfo, enterprise);
//            }
            cardEnterpriseTemplateDto.setFieldList(fieldList);
            if(StringUtils.isEmpty(cardEnterpriseTemplateDto.getLogoPosition()) || (!StringUtils.isEmpty(cardEnterpriseTemplateDto.getLogoPosition()) && !styleId.equals(cardEnterpriseTemplateDto.getLayoutNum()))){
                cardEnterpriseTemplateDto.setLogoPosition(cardTemplateStyle.getLogoPosition());
            }

            log.info("cardEnterpriseTemplateDto.getLayoutNum()的值::"+cardEnterpriseTemplateDto.getLayoutNum());
            log.info("styleId的值:"+styleId);
            if(StringUtils.isEmpty(cardEnterpriseTemplateDto.getBackgroundUrl()) || (!StringUtils.isEmpty(cardEnterpriseTemplateDto.getBackgroundUrl()) && !styleId.equals(cardEnterpriseTemplateDto.getLayoutNum()))){
                String backgroundUrl = cardTemplateStyle.getBackgroundUrl();
                if(!StringUtils.isEmpty(backgroundUrl)){
//                    LambdaQueryWrapper<CardTemplateBackground> backgroundWrapper = new LambdaQueryWrapper<CardTemplateBackground>()
//                            .eq(CardTemplateBackground::getStyleId, styleId)
//                            .eq(CardTemplateBackground::getTemplateType, templateType)
//                            .eq(!StringUtils.isEmpty(templateId), CardTemplateBackground::getTemplateId, templateId);
//                    List<CardTemplateBackground> backgroundList = cardTemplateBackgroundService.list(backgroundWrapper);
//                    if(!CollectionUtils.isEmpty(backgroundList)){
//                        Map<String, String> backgroundMap = backgroundList.stream()
//                                .collect(Collectors.toMap(
//                                        CardTemplateBackground::getBackgroundUrl,
//                                        CardTemplateBackground::getBaseId,
//                                        (existing, replacement) -> replacement
//                                ));
//                        log.info("backgroundMap:"+backgroundMap);
//                        log.info("backgroundMap.get(backgroundUrl):"+backgroundMap.get(backgroundUrl));
//                        cardEnterpriseTemplateDto.setBackgroundId(backgroundMap.get(backgroundUrl));
//                    }
                    cardEnterpriseTemplateDto.setBackgroundId(cardTemplateStyle.getDefaultBackgroundId());
                }


                cardEnterpriseTemplateDto.setBackgroundUrl(cardTemplateStyle.getBackgroundUrl());
            }
            cardEnterpriseTemplateDto.setLayoutNum(styleId);



        }else{
            return Message.fail("请选择样式");
        }

        return Message.success(cardEnterpriseTemplateDto);
    }

//    private void extracted(boolean appFlag, List<CardTemplateStyleField> fieldList, CardBaseInfo cardBaseInfo, LuLianEnterprise enterprise) {
//        CardLinkInfo cardLinkInfo = cardLinkInfoMapper.queryByBaseInfoId(cardBaseInfo.getBaseId());
//        String realname = cardBaseInfo.getName();
//        String commonName = cardBaseInfo.getEnterpriseName();
//        String mobile = cardBaseInfo.getEnterpriseMobile();
//        String userAddress = cardLinkInfo != null ? cardLinkInfo.getAddress() : "";
//        String userEmail = cardBaseInfo.getEnterpriseEmail();
//        String userFixedPhone = cardLinkInfo != null ? cardLinkInfo.getEmail() : "";
//        String userPositionOne = cardBaseInfo.getPositionOne();
//        String positionTwo = cardBaseInfo.getPositionTwo();
//        fieldList.forEach(field -> {
//            String fieldName = field.getFieldName();
//            String styleId = field.getStyleId();
//            Map<String, Object> extraInfo = new HashMap<>(field.getExtraInfo());
//            if("realname".equals(fieldName)){//真实姓名
//                if(!"8".equals(styleId)){
//                    extraInfo.put("text", realname);
//                }else if(appFlag){
//                    extraInfo.put("text", realname);
//                }
//
//            } else if ("username".equals(fieldName)) {//手机号
//                if(!StringUtils.isEmpty(mobile)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", mobile);
//                    }else if(appFlag){
//                        extraInfo.put("text", mobile);
//                    }
//
//                }else{
//                    if(appFlag){
//                        extraInfo.put("text", mobile);
//                    }
//                }
//            }else if ("commonName".equals(fieldName)) {//公司名称
//                String baseName = enterprise.getBaseName();
//
//                if(!StringUtils.isEmpty(commonName)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", commonName);
//                    }else if(appFlag){
//                        extraInfo.put("text", commonName);
//                    }
//
//                }else{
//                    if(!StringUtils.isEmpty(baseName)){
//                        if(!"8".equals(styleId)){
//                            extraInfo.put("text", baseName);
//                        }else if(appFlag){
//                            extraInfo.put("text", baseName);
//                        }
//
//                    }else{
//                        if(appFlag){
//                            extraInfo.put("text", baseName);
//                        }
//                    }
//                }
//
//            } else if ("webSite".equals(fieldName)) {//公司网站
//                String webSite = enterprise.getWebSite();
//                if(!"8".equals(styleId)){
//                    extraInfo.put("text", webSite);
//                }else if(appFlag){
//                    extraInfo.put("text", webSite);
//                }
//
//
//            }else if ("address".equals(fieldName)) {//地址
//                StringBuilder addressBuilder = new StringBuilder();
//                String address = enterprise.getAddress();
//                String province = enterprise.getProvince();
//                String city = enterprise.getCity();
//                String county = enterprise.getCounty();
//                List<SysArea> sysAreas = sysAreaMapper.selectList(new QueryWrapper<SysArea>().in("base_id", province, city, county));
//                Map<String, String> collect = new HashMap<>(16);
//                if(sysAreas != null && sysAreas.size() > 0){
//                    collect = sysAreas.stream().collect(Collectors.toMap(SysArea::getBaseId, SysArea::getBaseName));
//                }
//
//                String provinceStr = collect.get(province);
//                String cityStr = collect.get(city);
//                String regionStr = collect.get(county);
//
//                if (org.apache.commons.lang3.StringUtils.isNotBlank(provinceStr)) {
//                    addressBuilder.append(provinceStr);
//                }
//                if (org.apache.commons.lang3.StringUtils.isNotBlank(cityStr)) {
//                    if (! StrUtil.equals(provinceStr, cityStr)) {
//                        addressBuilder.append(cityStr);
//                    }
//                }
//                if (org.apache.commons.lang3.StringUtils.isNotBlank(regionStr)) {
//                    addressBuilder.append(regionStr);
//                }
//                if(org.apache.commons.lang3.StringUtils.isNotBlank(address)){
//                    addressBuilder.append(address);
//                }
//
//                address = !StringUtils.isEmpty(addressBuilder.toString()) ? addressBuilder.toString() : enterprise.getAddress();
//                if(!StringUtils.isEmpty(address)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", address);
//                    }else if(appFlag){
//                        extraInfo.put("text", address);
//                    }
//
//                }else{
//                    if(appFlag){
//                        extraInfo.put("text", address);
//                    }
//                }
//            }else if ("email".equals(fieldName)) {//邮箱
//                String email = "";
//                if(appFlag){
//                    email = userEmail;
//                }
//
//                if(!StringUtils.isEmpty(email)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", email);
//                    }else if(appFlag){
//                        extraInfo.put("text", email);
//                    }
//
//                }else{
//                    if(appFlag){
//                        extraInfo.put("text", email);
//                    }
//                }
//            }else if ("fixedPhone".equals(fieldName)) {//座机
//                String fiexedPhone = "";
//                if(appFlag){
//                    fiexedPhone = userFixedPhone;
//                }
//
//                if(!StringUtils.isEmpty(fiexedPhone)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", fiexedPhone);
//                    }else if(appFlag){
//                        extraInfo.put("text", fiexedPhone);
//                    }
//
//                }else{
//                    if(appFlag){
//                        extraInfo.put("text", fiexedPhone);
//                    }
//
//                }
//            }else if ("position".equals(fieldName)) {//职位
//                String position = "";
//                if(appFlag){
//                    position = userPositionOne + "|" + positionTwo;
//                }
//
//                if(!StringUtils.isEmpty(position)){
//                    if(!"8".equals(styleId)){
//                        extraInfo.put("text", position);
//                    }else if(appFlag){
//                        extraInfo.put("text", position);
//                    }
//
//                }else{
//                    if(appFlag){
//                        extraInfo.put("text", position);
//                    }
//                }
//            }
//             field.setExtraInfo(extraInfo);
//
//        });
//    }

    private void processTemplateInfo(CardEnterpriseTemplateDto dto, boolean newFlag) {
        List<CardTemplateStyleField> fieldList = dto.getFieldList();
        String templateId = dto.getBaseId();
        String enterpriseId = dto.getEnterpriseId();
        LambdaUpdateWrapper<CardTemplateStyleField> fieldWrapper = new LambdaUpdateWrapper<>();
        fieldWrapper.eq(CardTemplateStyleField::getTemplateId, templateId);


        List<CardTemplateStyleField> existFieldList = styleFieldService.list(fieldWrapper);

        Map<String, String> fieldMap = existFieldList.stream()
                .collect(Collectors.toMap(
                        CardTemplateStyleField::getFieldName,
                        CardTemplateStyleField::getBaseId
                ));

        styleFieldService.remove(fieldWrapper);
        fieldList.forEach(field -> {
            if(StringUtils.isEmpty(field.getBaseId()) && fieldMap.get(field.getFieldName()) != null){
                field.setBaseId(fieldMap.get(field.getFieldName()));
            }
            field.setTemplateId(templateId);
            field.setStyleId(dto.getLayoutNum());
            field.setBaseCreateTime(new Date());
            field.setTemplateType(dto.getTemplateType());
        });
        styleFieldService.saveBatch(fieldList);


        if(!CollectionUtils.isEmpty(fieldList)){

            if(!newFlag){
                // 获取新增的字段
                List<CardTemplateStyleField> toAddList = fieldList.stream()
                        .filter(field -> existFieldList.stream()
                                .noneMatch(exist -> Objects.equals(exist.getBaseId(), field.getBaseId())))
                        .collect(Collectors.toList());

                // 获取删除的字段
                List<CardTemplateStyleField> toDeleteList = existFieldList.stream()
                        .filter(exist -> fieldList.stream()
                                .noneMatch(field -> Objects.equals(exist.getBaseId(), field.getBaseId())))
                        .collect(Collectors.toList());

                // 查出所有使用该模板的名片，在每一张名片的组件数据中添加新组件
                List<String> useCurTemplateCardIdList = cardAuditMapper.queryCardIdList(dto.getNewTemplateId(), null);
                if(!CollectionUtils.isEmpty(useCurTemplateCardIdList)){
                    // todo 这里可以优化为批量删除 delete where styleFieldId in ()
                    for (CardTemplateStyleField deleteField : toDeleteList){
                        String fieldId = deleteField.getBaseId();
                        cardStyleFieldDataMapper.delete(new LambdaQueryWrapper<CardStyleFieldData>().eq(CardStyleFieldData::getStyleFieldId, fieldId).in(CardStyleFieldData::getCardId, useCurTemplateCardIdList));
                    }
                    // todo 下面可以优化为批量保存
                    for (CardTemplateStyleField addField : toAddList){
                        for(String cardId : useCurTemplateCardIdList){
                            CardStyleFieldData newfieldData = new CardStyleFieldData();
                            newfieldData.setBaseId(IdUtil.simpleUUID());
                            String fieldId = addField.getBaseId();
                            newfieldData.setStyleFieldId(fieldId);
                            newfieldData.setCardId(cardId);
                            Boolean employeeEditFlag = addField.getEmployeeEditFlag();
                            if(employeeEditFlag != null && !employeeEditFlag){
                                Map<String, Object> extraInfo = addField.getExtraInfo();
                                Object text = extraInfo.get("text");
                                newfieldData.setStyleFieldValue(text == null ? null : String.valueOf(text));
                            }
                            cardStyleFieldDataMapper.insert(newfieldData);
                        }

                    }


                }
            }


        }else{
            if(!newFlag) {

                if(!CollectionUtils.isEmpty(existFieldList)){
                    // 获取删除的字段
                    List<CardTemplateStyleField> toDeleteList = existFieldList;

                    // 查出所有使用该模板的名片，在每一张名片的组件数据中添加新组件
                    List<String> useCurTemplateCardIdList = cardAuditMapper.queryCardIdList(dto.getNewTemplateId(), null);
                    if (!CollectionUtils.isEmpty(useCurTemplateCardIdList)) {
                        for (CardTemplateStyleField deleteField : toDeleteList) {
                            String fieldId = deleteField.getBaseId();
                            cardStyleFieldDataMapper.delete(new LambdaQueryWrapper<CardStyleFieldData>().eq(CardStyleFieldData::getStyleFieldId, fieldId).in(CardStyleFieldData::getCardId, useCurTemplateCardIdList));
                        }
                    }
                }

            }

        }
        List<String> selectedBackgroundIdList = dto.getSelectedBackgroundIds();
        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaQueryWrapper<CardTemplateBackground> wrapper = new LambdaQueryWrapper<CardTemplateBackground>().isNull(CardTemplateBackground::getTemplateId)
                    .eq(CardTemplateBackground::getEnterpriseId, dto.getEnterpriseId()).eq(CardTemplateBackground::getCreateCardId, dto.getEnterpriseAdminCardId())
                    .eq(CardTemplateBackground::getStyleId, dto.getLayoutNum())
                    .eq(CardTemplateBackground::getTemplateType, dto.getTemplateType())
            .notIn(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.remove(wrapper);
        }

        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaUpdateWrapper<CardTemplateBackground> backgroundWrapper = new LambdaUpdateWrapper<>();
            backgroundWrapper.set(CardTemplateBackground::getTemplateId, templateId).set(CardTemplateBackground::getTemplateType, dto.getTemplateType()).in(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.update(backgroundWrapper);
        }

    }


    @Override
    public Message preTemplateStyleDetail(String styleId, String templateId, String templateType, String version) {
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();



        if(!StringUtils.isEmpty(templateId)){
            template = this.getById(templateId);

        }

        CardEnterpriseTemplateDto cardEnterpriseTemplateDto = new CardEnterpriseTemplateDto();
        BeanUtils.copyProperties(template, cardEnterpriseTemplateDto);
        if(!StringUtils.isEmpty(styleId)){

            CardTemplateStyle cardTemplateStyle = cardTemplateStyleService.preStyleDetail(styleId, templateId, templateType);
            List<CardTemplateStyleField> fieldList = cardTemplateStyle.getFieldList();
            cardEnterpriseTemplateDto.setFieldList(fieldList);
            if(StringUtils.isEmpty(cardEnterpriseTemplateDto.getLogoPosition()) || (!StringUtils.isEmpty(cardEnterpriseTemplateDto.getLogoPosition()) && !styleId.equals(cardEnterpriseTemplateDto.getLayoutNum()))){
                cardEnterpriseTemplateDto.setLogoPosition(cardTemplateStyle.getLogoPosition());
            }
            if(StringUtils.isEmpty(cardEnterpriseTemplateDto.getBackgroundUrl()) || (!StringUtils.isEmpty(cardEnterpriseTemplateDto.getBackgroundUrl()) && !styleId.equals(cardEnterpriseTemplateDto.getLayoutNum()))){
                String backgroundUrl = cardTemplateStyle.getBackgroundUrl();
                if(!StringUtils.isEmpty(backgroundUrl)){
//                    LambdaQueryWrapper<CardTemplateBackground> backgroundWrapper = new LambdaQueryWrapper<CardTemplateBackground>()
//                            .and(w -> w.isNull(CardTemplateBackground::getTemplateId)
//                                    .or(andWrapper -> andWrapper
//                                            .eq(CardTemplateBackground::getTemplateId, templateId)
//
//                                    )
//                            )
//                            .eq(CardTemplateBackground::getStyleId, styleId)
//                            .eq(CardTemplateBackground::getCustomFlag, false)
//                            .eq(!StringUtils.isEmpty(version),CardTemplateBackground::getVersion, version)
//
//                            .eq(!StringUtils.isEmpty(templateId), CardTemplateBackground::getTemplateId, templateId);
//                    List<CardTemplateBackground> backgroundList = cardTemplateBackgroundService.list(backgroundWrapper);
//                    if(!CollectionUtils.isEmpty(backgroundList)){
//                        Map<String, String> backgroundMap = backgroundList.stream()
//                                .collect(Collectors.toMap(
//                                        CardTemplateBackground::getBackgroundUrl,
//                                        CardTemplateBackground::getBaseId,
//                                        (existing, replacement) -> replacement
//                                ));
//                        cardEnterpriseTemplateDto.setBackgroundId(backgroundMap.get(backgroundUrl));
//                    }

                    cardEnterpriseTemplateDto.setBackgroundId(cardTemplateStyle.getDefaultBackgroundId());
                }


                cardEnterpriseTemplateDto.setBackgroundUrl(cardTemplateStyle.getBackgroundUrl());
            }

            cardEnterpriseTemplateDto.setLayoutNum(styleId);

        }

        return Message.success(cardEnterpriseTemplateDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message savePreTemplate(CardEnterpriseTemplateDto dto) {
        dto.setBaseId(UUIDUtil.getUUID());
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        processPreTemplateInfo(dto, true);
        BeanUtils.copyProperties(dto, template);
        this.save(template);
        return Message.success();
    }

    @Override
    public Message updatePreTemplate(CardEnterpriseTemplateDto dto) {
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        processPreTemplateInfo(dto, false);
        BeanUtils.copyProperties(dto, template);
        this.updateById(template);
        return Message.success();
    }

    private void processPreTemplateInfo(CardEnterpriseTemplateDto dto, boolean newFlag) {
        List<CardTemplateStyleField> fieldList = dto.getFieldList();
        String templateId = dto.getBaseId();
        LambdaUpdateWrapper<CardTemplateStyleField> fieldWrapper = new LambdaUpdateWrapper<>();
        fieldWrapper.eq(CardTemplateStyleField::getTemplateId, templateId);



        styleFieldService.remove(fieldWrapper);

        if(!CollectionUtils.isEmpty(fieldList)){
            fieldList.forEach(field -> {
                field.setBaseId(UUIDUtil.getUUID2());
                field.setTemplateId(templateId);
                field.setStyleId(dto.getLayoutNum());
                field.setBaseCreateTime(new Date());
                field.setTemplateType(dto.getTemplateType());
            });
            styleFieldService.saveBatch(fieldList);
        }
        List<String> selectedBackgroundIdList = dto.getSelectedBackgroundIds();
        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaQueryWrapper<CardTemplateBackground> wrapper = new LambdaQueryWrapper<CardTemplateBackground>().isNull(CardTemplateBackground::getTemplateId)
                    .isNull(CardTemplateBackground::getEnterpriseId).isNull(CardTemplateBackground::getCreateCardId)
                    .eq(CardTemplateBackground::getStyleId, dto.getLayoutNum())
                    .eq(CardTemplateBackground::getTemplateType, dto.getTemplateType())
                    .eq(CardTemplateBackground::getVersion, dto.getVersion())
                    .notIn(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.remove(wrapper);
        }

        if(!CollectionUtils.isEmpty(selectedBackgroundIdList)){
            LambdaUpdateWrapper<CardTemplateBackground> backgroundWrapper = new LambdaUpdateWrapper<>();
            backgroundWrapper.set(CardTemplateBackground::getTemplateId, templateId).set(CardTemplateBackground::getTemplateType, dto.getTemplateType()).in(CardTemplateBackground::getBaseId, selectedBackgroundIdList);
            templateBackgroundService.update(backgroundWrapper);
        }

    }

    @Override
    public void deleteByNewTemplateId(String newTemplateId) {
        List<CardEnterpriseTemplate> list = this.list(new LambdaQueryWrapper<CardEnterpriseTemplate>().eq(CardEnterpriseTemplate::getNewTemplateId, newTemplateId));
        for (CardEnterpriseTemplate template : list){
            cardTemplateBackgroundService.remove(new LambdaQueryWrapper<CardTemplateBackground>().eq(CardTemplateBackground::getTemplateId,template.getBaseId()));
            cardTemplateStyleFieldService.remove(new LambdaQueryWrapper<CardTemplateStyleField>().eq(CardTemplateStyleField::getTemplateId,template.getBaseId()));

        }
        this.remove(new LambdaQueryWrapper<CardEnterpriseTemplate>().eq(CardEnterpriseTemplate::getNewTemplateId, newTemplateId));

    }
}
